# -*- coding: utf-8 -*-
import ezdxf
import json

from uuid import uuid1
from ezdxf.addons import odafc
from sqlalchemy import func

from app.models import db_session
from app.models.model import *
from app.configs import sys_type
from app.tools.utils import *
from app.models.cod import Model, ValkyrjaException, Error

# ODAFileConverter: windows环境、linux环境
exec_path = r'ODAFileConverter'
if sys_type == 'Windows':
    exec_path = r'C:\Program Files\ODA\ODAFileConverter 23.3.0\ODAFileConverter.exe'


def clear(meta_id):
    session = db_session()
    for model in Model:
        if model.name == "Mine":
            continue
        M = model.value
        items = session.query(M).filter(M.meta_id == meta_id).all()
        for item in items:
            session.delete(item)
    session.commit()
    session.close()


def clear_all(meta_id=None):
    session = db_session()
    for model in Model:
        M, values = model.value, None
        if meta_id is None:
            values = session.query(M).all()
        else:
            values = session.query(M).filter(M.meta_id == meta_id).all()
        for item in values:
            session.delete(item)
    session.commit()
    session.close()


def db2meta(meta_id):
    session, M = db_session(), MetaModel
    metas = session.query(M).filter(M.meta_id == meta_id).all()
    if len(metas) == 0:
        raise ValkyrjaException(Error.NotMeta)
    meta = metas[0]
    session.close()
    return meta.dxf()


def db2header(meta_id):
    session, M = db_session(), HeaderModel
    headers = session.query(M).filter(M.meta_id == meta_id).all()
    if len(headers) < 1:
        raise ValkyrjaException(Error.FmtError)
    header = headers[0]
    session.close()
    return header.dxf()


def db2layout(meta_id):
    session, M = db_session(), LayoutModel
    layouts = session.query(M).filter(M.meta_id == meta_id).all()
    if len(layouts) < 1:
        raise ValkyrjaException(Error.FmtError)
    session.close()
    return layouts[0]


def db2viewport(meta_id):
    session, M = db_session(), ViewportModel
    viewports = session.query(M).filter(M.meta_id == meta_id).all()
    if len(viewports) < 1:
        raise ValkyrjaException(Error.FmtError)
    session.close()
    return viewports[0]


def db2entities(cls, meta_id=None):
    session = db_session()
    if meta_id is None:
        features = session.query(cls).all()
    else:
        features = session.query(cls).filter(cls.meta_id == meta_id).all()
    session.close()
    return [feature.dxf() for feature in features]


def metas():
    session = db_session()
    db_metas = session.query(MetaModel).all()
    session.close()
    return [meta.dxf() for meta in db_metas]


def db2vectors(cls, meta_id):
    session = db_session()
    features = session.query(cls).filter(cls.meta_id == meta_id).all()
    session.close()
    return [feature.vector() for feature in features]


def vectors(meta_id):
    return {
        'meta': db2meta(meta_id),
        'layers': db2vectors(LayerModel, meta_id),
        'entities': {
            'lwpolylines': db2vectors(LWPolylineModel, meta_id),
            'texts': db2vectors(TextModel, meta_id),
            'lines': db2vectors(LineModel, meta_id),
            'mtexts': db2vectors(MTextModel, meta_id),
            'circles': db2vectors(CircleModel, meta_id),
            'arcs': db2vectors(ArcModel, meta_id),
            'splines': db2vectors(SplineModel, meta_id),
            'polylines': db2vectors(PolylineModel, meta_id),
            'ellipses': db2vectors(EllipseModel, meta_id),
            'hatches': db2vectors(HatchModel, meta_id),
            'tracks': db2vectors(TrackModel, meta_id),
            'positions': db2vectors(PositionModel, meta_id),
            'tunnels': db2vectors(TunnelModel, meta_id),
            'guide_points': db2vectors(GuidePointModel, meta_id),
            'faults': db2vectors(FaultModel, meta_id),
            'warnings': db2vectors(WarningModel, meta_id),
            'monitors': db2vectors(MonitorModel, meta_id),
            'inserts': db2vectors(InsertModel, meta_id),
            'smgas': db2vectors(SMGasModel, meta_id),
            'smstaff': db2vectors(SMStaff, meta_id),
            'smbroadcast': db2vectors(SMBroadCastModel, meta_id),
            'smvideo': db2vectors(SMVideoModel, meta_id),
            'smventilate': db2vectors(SMVentilateModel, meta_id),
            'smpoweredarea': db2vectors(SMPoweredAreaModel, meta_id)
        }
    }


def db2vectorss(cls, meta_ids):
    session = db_session()
    features = session.query(cls).filter(cls.meta_id.in_(meta_ids)).all()
    session.close()
    return [feature.vector() for feature in features]


def vectorss(meta_ids):
    return {
        'meta': db2meta(meta_ids[0]),
        'layers': db2vectorss(LayerModel, meta_ids),
        'entities': {
            'lwpolylines': db2vectorss(LWPolylineModel, meta_ids),
            'texts': db2vectorss(TextModel, meta_ids),
            'lines': db2vectorss(LineModel, meta_ids),
            'mtexts': db2vectorss(MTextModel, meta_ids),
            'circles': db2vectorss(CircleModel, meta_ids),
            'arcs': db2vectorss(ArcModel, meta_ids),
            'splines': db2vectorss(SplineModel, meta_ids),
            'polylines': db2vectorss(PolylineModel, meta_ids),
            'ellipses': db2vectorss(EllipseModel, meta_ids),
            'hatches': db2vectorss(HatchModel, meta_ids),
            'tracks': db2vectorss(TrackModel, meta_ids),
            'positions': db2vectorss(PositionModel, meta_ids),
            'tunnels': db2vectorss(TunnelModel, meta_ids),
            'guide_points': db2vectorss(GuidePointModel, meta_ids),
            'faults': db2vectorss(FaultModel, meta_ids),
            'warnings': db2vectorss(WarningModel, meta_ids),
            'inserts': db2vectorss(InsertModel, meta_ids)
        }
    }


def add(obj):
    session = db_session()
    session.add(obj)
    session.commit()
    session.close()


def delete(cls, id):
    session = db_session()
    session.query(cls).filter(cls.id == id).delete()
    session.commit()
    session.close()

def update(cls, id, data):
    session = db_session()
    row = session.query(cls).filter(cls.id == id).first()
    keys = tuple(data.keys())
    vals = tuple(data.values())
    for i in range(len(keys)):
        setattr(row,keys[i],vals[i])
    session.commit()
    session.close()

def deleteSmVentilate(cls,mine_id,meta_id,id):
    session = db_session()
    session.query(cls).filter(cls.id == id and cls.mine_id == mine_id and cls.meta_id == meta_id).delete()
    session.commit()
    session.close()

def col_max(col):
    session = db_session()
    max = session.query(func.max(col)).one()
    return max[0]


def vertices2str(vertices):
    str = ''
    for v in vertices:
        l = v.dxf.location
        vertex = {
            'location': (l[0], l[1], l[2]),
            'start_width': v.dxf.start_width,
            'end_width': v.dxf.end_width,
            'bulge': v.dxf.bulge,
            'flags': v.dxf.flags,
            'tangent': v.dxf.tangent,
            'vtx0': v.dxf.vtx0,
            'vtx1': v.dxf.vtx1,
            'vtx2': v.dxf.vtx2,
            'vtx3': v.dxf.vtx3,
            'vertex_identifier': v.dxf.vertex_identifier,
            'is_2d_polyline_vertex': v.is_2d_polyline_vertex,
            'is_3d_polyline_vertex': v.is_3d_polyline_vertex,
            'is_polygon_mesh_vertex': v.is_polygon_mesh_vertex,
            'is_poly_face_mesh_vertex': v.is_poly_face_mesh_vertex,
            'is_face_record': v.is_face_record
        }
        str += json.dumps(vertex) + ';'
    return str.rstrip(';')


def str2vertices(str: str):
    vertices = []
    for s in str.split(';'):
        obj = json.loads(s)
        v = (
            obj['location'][0],
            obj['location'][1],
            obj['start_width'],
            obj['end_width'],
            obj['bulge']
        )
        vertices.append(v)
    return vertices


def _entity(session, entity, l, r, t, b, meta_id, insert_id=None):
    if entity.dxftype() == 'LWPOLYLINE':
        with entity.points('xy') as points:
            for p in points:
                l, r, t, b = box(l, r, t, b, p)
        lwpolyline = LWPolylineModel(entity, meta_id, insert_id)
        session.add(lwpolyline)
    elif entity.dxftype() == 'TEXT':
        l, r, t, b = box(l, r, t, b, [entity.dxf.insert.x, entity.dxf.insert.y])
        text = TextModel(entity, meta_id, insert_id)
        session.add(text)
    elif entity.dxftype() == 'LINE':
        l, r, t, b = box(l, r, t, b, [entity.dxf.start.x, entity.dxf.start.y])
        l, r, t, b = box(l, r, t, b, [entity.dxf.end.x, entity.dxf.end.y])
        line = LineModel(entity, meta_id, insert_id)
        session.add(line)
    elif entity.dxftype() == 'MTEXT':
        l, r, t, b = box(l, r, t, b, [entity.dxf.insert.x, entity.dxf.insert.y])
        mtext = MTextModel(entity, meta_id, insert_id)
        session.add(mtext)
    elif entity.dxftype() == 'ELLIPSE':
        l, r, t, b = box(l, r, t, b, [entity.dxf.center.x, entity.dxf.center.y])
        ellipse = EllipseModel(entity, meta_id, insert_id)
        session.add(ellipse)
    elif entity.dxftype() == 'HATCH':
        if len(entity.seeds) > 0:
            l, r, t, b = box(l, r, t, b, [entity.seeds[0][0], entity.seeds[0][1]])
        hatch = HatchModel(entity, meta_id, insert_id)
        session.add(hatch)
    elif entity.dxftype() == 'CIRCLE':
        l, r, t, b = box(l, r, t, b, [entity.dxf.center.x, entity.dxf.center.y])
        circle = CircleModel(entity, meta_id, insert_id)
        session.add(circle)
    elif entity.dxftype() == 'ARC':
        l, r, t, b = box(l, r, t, b, [entity.dxf.center.x, entity.dxf.center.y])
        arc = ArcModel(entity, meta_id, insert_id)
        session.add(arc)
    elif entity.dxftype() == 'SPLINE':
        spline = SplineModel(entity, meta_id, insert_id)
        session.add(spline)
    elif entity.dxftype() == 'POLYLINE' and entity.is_2d_polyline:
        for v in entity.vertices:
            l, r, t, b = box(l, r, t, b, v.dxf.location.vec2)
        polyline = PolylineModel(entity, meta_id, insert_id)
        session.add(polyline)
    elif entity.dxftype() == 'DIMENSION':
        dimension = DimensionModel(entity, meta_id, insert_id)
        session.add(dimension)
    elif entity.dxftype() == 'SOLID':
        l, r, t, b = box(l, r, t, b, [entity.dxf.vtx0.x, entity.dxf.vtx0.y])
        l, r, t, b = box(l, r, t, b, [entity.dxf.vtx1.x, entity.dxf.vtx1.y])
        l, r, t, b = box(l, r, t, b, [entity.dxf.vtx2.x, entity.dxf.vtx2.y])
        l, r, t, b = box(l, r, t, b, [entity.dxf.vtx3.x, entity.dxf.vtx3.y])
        solid = SolidModel(entity, meta_id, insert_id)
        session.add(solid)
    elif entity.dxftype() == 'POINT':
        l, r, t, b = box(l, r, t, b, [entity.dxf.location.x, entity.dxf.location.y])
        point = PointModel(entity, meta_id, insert_id)
        session.add(point)
    elif entity.dxftype() != 'INSERT':
        print(entity.dxftype())

    return l, r, t, b


def doc2db(doc, meta):
    meta_id = meta['meta_id'] if meta['meta_id'] else 'default'
    session, msp = db_session(), doc.modelspace()
    l, r, t, b = None, None, None, None

    # 获取header信息
    header = HeaderModel(doc=doc, meta_id=meta_id)
    session.add(header)

    #  获取styles信息
    for layer, entity in doc.styles.entries.items():
        style = StyleModel(entity=entity, meta_id=meta_id)
        session.add(style)

    #  获取dimstyles信息
    for _, entity in doc.dimstyles.entries.items():
        dimstyle = DimstyleModel(entity, meta_id)
        session.add(dimstyle)

    # 获取viewport信息
    viewportdxf = doc.viewports.entries['*active'][0].dxf
    viewport = ViewportModel(viewportdxf, meta_id=meta_id)
    session.add(viewport)

    # 获取layout信息
    layout = LayoutModel(msp.dxf, meta_id=meta_id)
    session.add(layout)

    # 获取图层信息
    for _, entity in doc.layers.entries.items():
        layer = LayerModel(entity, meta_id)
        session.add(layer)

    # 获取线形信息
    for linetype in doc.linetypes:
        lt = LinetypeModel(entity=linetype, meta_id=meta_id)
        session.add(lt)

    # 添加形状类型
    for entity in msp:
        if entity.dxftype() == 'INSERT':
            l, r, t, b = box(l, r, t, b, [entity.dxf.insert.x, entity.dxf.insert.y])
            insert_id = str(uuid1())
            insert = InsertModel(entity, meta_id, insert_id)
            blocks = doc.blocks.get(entity.dxf.name)
            if blocks is not None:
                insert.base = largebinary_dumps([blocks.base_point[0], blocks.base_point[1]])
                session.add(insert)
                for block in blocks:
                    l, r, t, b = _entity(session, block, l, r, t, b, meta_id, insert_id)
        else:
            l, r, t, b = _entity(session, entity, l, r, t, b, meta_id)

    # 设置meta中的边界信息
    name = meta['name'] if meta['name'] else 'default'
    mm = MetaModel(name=name, meta_id=meta_id)
    mm.mine_code = meta['mine_code'] if meta['mine_code'] else 'default'
    mm.mine_name = meta['mine_name'] if meta['mine_name'] else 'default'
    mm.sign = meta['sign'] if meta['sign'] else 'default'
    mm.type = meta['type'] if meta['type'] else 'default'
    mm.piece = meta['piece'] if meta['piece'] else 'default'
    mm.major_ver = meta['major_ver'] if meta['major_ver'] else 'default'
    mm.minor_ver = meta['minor_ver'] if meta['minor_ver'] else 'default'
    mm.cs = meta['cs'] if meta['cs'] else 'default'
    mm.left, mm.right, mm.top, mm.bottom = l, r, t, b

    # 这里着重处理CAD的视图中心点
    vtx, vty = viewportdxf.target.x, viewportdxf.target.y
    vcx, vcy = viewportdxf.center.x, viewportdxf.center.y
    if math.fabs(vtx) < THRESHOLD and math.fabs(vty) < THRESHOLD:
        mm.x, mm.y = vcx, vcy
        angle = viewportdxf.view_twist
        if angle == 0:
            mm.x, mm.y = vcx, vcy
        else:
            mm.x, mm.y = twist(vcx, vcy, angle)
    else:
        mm.x, mm.y = vtx, vty
    session.add(mm)

    session.commit()
    session.close()

    return meta_id


def _msp(doc, msp, defs, entity):
    result = msp
    if entity['insert_id'] is not None:
        name = defs.get(entity['insert_id'])
        result = doc.blocks[name]
    return result


def db2doc(doc, meta_id):
    msp, meta = doc.modelspace(), db2meta(meta_id)

    # 设置viewport
    viewport = db2viewport(meta['meta_id'])
    viewport.dxf_viewport(doc.viewports.entries['*active'][0].dxf)

    # 设置layout
    layout = db2layout(meta['meta_id'])
    layout.dxf_layout(msp.dxf_layout)

    # 添加图层数据
    layers = db2entities(LayerModel, meta['meta_id'])
    for layer in layers:
        name, linetype, color = layer['name'], layer['linetype'], layer['color']
        if name not in doc.layers:
            doc.layers.new(name=name, dxfattribs={'color': color})

    # 设置styles
    styles = db2entities(StyleModel, meta['meta_id'])
    for style in styles:
        name = style['dxf']['name']
        if name not in doc.styles:
            doc.styles.new(name=name, dxfattribs=style['dxf'])
        else:
            doc.styles.remove(name)
            doc.styles.new(name=name, dxfattribs=style['dxf'])

    # 获取线型数据
    # linetypes = db2entities(LinetypeModel, meta['meta_id'])
    # for linetype in linetypes:
    #     name, is_complex_type = linetype['dxf']['name'], linetype['is_complex_type']
    #     if name in doc.linetypes:
    #         entity = doc.linetypes.get(name)
    #         entity.pattern_tags.tags = linetype['tags'].tags
    #     else:
    #         if is_complex_type:
    #             print('Exdxf暂时不支持Complex Linetype => ', linetype)
    #         else:
    #             if len(linetype['pattern']) == 0:
    #                 continue
    #             entity = doc.linetypes.add(
    #                 name=name,
    #                 pattern=linetype['pattern'],
    #                 description=linetype['dxf']['description'],
    #                 dxfattribs=linetype['dxf']
    #             )
    #             entity.pattern_tags.tags = linetype['tags'].tags

    # 设置dimstyles
    # dimstyles = db2entities(DimstyleModel, meta['meta_id'])
    # for dimstyle in dimstyles:
    #     name = dimstyle['dxf']['name']
    #     if name not in doc.styles:
    #         doc.dimstyles.add(name=name, dxfattribs=dimstyle['dxf'])
    #     else:
    #         doc.dimstyles.remove(name)
    #         doc.dimstyles.new(name=name, dxfattribs=dimstyle['dxf'])

    # # 添加dimension格式数据
    # dimensions = db2entities(DimensionModel, meta['meta_id'])
    # for dimension in dimensions:
    #     print('Exdxf暂时不支持dimension类型 => ', dimension)

    # 添加insert格式数据,建立insert_id与block名称对应表,设置base_point
    mb, defs, inserts = None, dict(), db2entities(InsertModel, meta['meta_id'])
    for insert in inserts:
        name, point = insert['dxf']['name'], insert['dxf']['insert']
        base, insert_id = insert['base'], insert['insert_id']
        defs[insert_id] = name
        msp.add_blockref(name=name, insert=point, dxfattribs=insert['dxf'])
        if doc.blocks.get(name) is None:
            block = doc.blocks.new(name=name)
            block.block.dxf.base_point = base

    # 添加hatch格式数据
    hatches = db2entities(HatchModel, meta['meta_id'])
    for hatch in hatches:
        solid_fill, color = hatch['dxf']['solid_fill'], hatch['dxf']['color']
        mb, hatch_style = _msp(doc, msp, defs, hatch), hatch['dxf']['hatch_style']

        # 申请一个hatch对象
        h = mb.add_hatch(color=color, dxfattribs={'hatch_style': hatch_style})

        # 设置填充方式
        if hatch['dxf']['solid_fill'] == 0:
            h.set_solid_fill(color=color, style=hatch_style)
        else:
            h.set_pattern_fill(
                name=hatch['dxf']['pattern_name'],
                color=color,
                angle=hatch['dxf']['pattern_angle'],
                scale=hatch['dxf']['pattern_scale'],
                double=hatch['dxf']['pattern_double'],
                pattern_type=hatch['dxf']['pattern_type'],
                definition=None
            )

        # # 存在seeds的情况下,seeds是在OCS坐标系使用
        # if len(hatch['seeds']) > 0:
        #     h.set_seed_points(hatch['seeds'])
        #
        # 存在渐变的情况
        gradient = hatch['gradient']
        if gradient is not None:
            h.set_gradient(
                color1=gradient.color1,
                color2=gradient.color2,
                rotation=gradient.rotation,
                centered=gradient.centered,
                one_color=gradient.one_color,
                tint=gradient.tint,
                name=gradient.name
            )

        # 添加路径
        for path in hatch['paths']:
            name, flags = type(path).__name__, path.path_type_flags
            if name == 'PolylinePath':
                h.paths.add_polyline_path(path.vertices, is_closed=path.is_closed, flags=1)
            else:
                edge_path = h.paths.add_edge_path(flags=1)
                for e in path.edges:
                    edge_type = e.EDGE_TYPE
                    if edge_type == 'LineEdge':
                        edge_path.add_line(e.start, e.end)
                    elif edge_type == 'ArcEdge':
                        c, r, sa, ea = e.center, e.radius, e.start_angle, e.end_angle
                        edge_path.add_arc(center=c, radius=r, start_angle=sa, end_angle=ea)
                    elif edge_type == 'SplineEdge':
                        edge_path.add_spline(control_points=e.control_points, knot_values=e.knot_values)
                    elif edge_type == 'EllipseEdge':
                        c, m, r, sa, ea = e.center, e.major_axis, e.ratio, e.start_angle, e.end_angle
                        edge_path.add_ellipse(center=c, major_axis=m, ratio=r, start_angle=sa, end_angle=ea)

    # 添加lwpolyline格式数据
    lwpolylines = db2entities(LWPolylineModel, meta['meta_id'])
    for lwpolyline in lwpolylines:
        mb = _msp(doc, msp, defs, lwpolyline)
        pts, c, dxf = lwpolyline['points'], lwpolyline['closed'], lwpolyline['dxf']
        mb.add_lwpolyline(points=pts, close=c, dxfattribs=dxf)

    # 添加line格式数据
    lines = db2entities(LineModel, meta['meta_id'])
    for line in lines:
        mb = _msp(doc, msp, defs, line)
        mb.add_line(line['start'], line['end'], line['dxf'])

    # 添加polyline2D格式数据
    polylines = db2entities(PolylineModel, meta['meta_id'])
    for polyline in polylines:
        mb = _msp(doc, msp, defs, polyline)
        if polyline['is_2d_polyline']:
            v, f, c = polyline['vertices'], 'xy', polyline['is_closed']
            mb.add_polyline2d(points=v, format=f, close=c, dxfattribs=polyline['dxf'])
        else:
            print("There is no resolution except for polyline2d")

    # 添加spline格式数据
    splines = db2entities(SplineModel, meta['meta_id'])
    for spline in splines:
        mb = _msp(doc, msp, defs, spline)
        fit_points, degree, dxf = spline['fit_points'], spline['dxf']['degree'], spline['dxf']
        if fit_points is not None:
            mb.add_spline(fit_points, degree=degree, dxfattribs=dxf)
        control_points = spline['control_points']
        if control_points is not None:
            mb.add_open_spline(control_points, degree=degree, dxfattribs=dxf)
            weights = spline['weights']
            if weights is not None:
                mb.add_rational_spline(control_points, weights=weights, dxfattribs=dxf)

    # 添加circle格式数据
    circles = db2entities(CircleModel, meta['meta_id'])
    for circle in circles:
        mb = _msp(doc, msp, defs, circle)
        mb.add_circle(center=circle['center'], radius=circle['radius'])

    # 添加ellipse格式数据
    ellipses = db2entities(EllipseModel, meta['meta_id'])
    for ellipse in ellipses:
        mb = _msp(doc, msp, defs, ellipse)
        mb.add_ellipse(
            center=ellipse['center'],
            major_axis=ellipse['major_axis'],
            ratio=ellipse['ratio'],
            start_param=ellipse['start_param'],
            end_param=ellipse['end_param']
        )

    # 添加arc格式数据
    arcs = db2entities(ArcModel, meta['meta_id'])
    for arc in arcs:
        mb = _msp(doc, msp, defs, arc)
        mb.add_arc(
            center=arc['center'],
            radius=arc['radius'],
            start_angle=arc['start_angle'],
            end_angle=arc['end_angle'],
            dxfattribs=arc['dxf']
        )

    # 添加point格式数据
    points = db2entities(PointModel, meta['meta_id'])
    for point in points:
        mb = _msp(doc, msp, defs, point)
        mb.add_point(
            location=point['dxf']['location'],
            dxfattribs=point['dxf']
        )

    # 添加text格式数据
    texts = db2entities(TextModel, meta['meta_id'])
    for text in texts:
        mb = _msp(doc, msp, defs, text)
        mb.add_text(text['text'], dxfattribs=text['dxf'])

    # 添加mtext格式数据
    mtexts = db2entities(MTextModel, meta['meta_id'])
    for mtext in mtexts:
        mb = _msp(doc, msp, defs, mtext)
        mb.add_mtext(mtext['text'], mtext['dxf'])


def dxf2db(file, meta):
    doc = ezdxf.readfile(filename=file, encoding='utf-8')
    doc2db(doc, meta)


def db2dxf(file, meta_id):
    doc = ezdxf.new()
    doc.styles.add("Arial", font="Arial.ttf")
    db2doc(doc, meta_id)
    doc.saveas(file)


def dwg2db(file, meta):
    ezdxf.options.set('odafc-addon', 'win_exec_path', exec_path)
    doc = odafc.readfile(file)
    doc2db(doc, meta)


def db2dwg(file, meta_id):
    doc = ezdxf.new()
    doc.styles.add("Arial", font="Arial.ttf")
    db2doc(doc, meta_id)
    odafc.export_dwg(doc, file)
